using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;

using Janus.Windows.GridEX;
namespace Janus.NorthwindDemo2007
{
	public partial class OrderDataForm
	{

		protected override void StartEdition()
		{

			DataRowView dataRow = null;
			dataRow = this.DataRowView;

			if (this.EditMode == DataFormEditMode.AddNew)
			{
				this.Text = "Orders - New Order";
			}
			else
			{
				this.Text = "Orders - Order # " + dataRow["OrderID"];
				this.FillDetails((int)dataRow["OrderID"]);
			}
			this.SetBindings();
			if (! System.Convert.IsDBNull(dataRow["CustomerID"]))
			{

				NorthwindData.CustomersRow customer = null;
				customer = this.GetCustomerRow((string)dataRow["CustomerID"]);
				this.FillCustomerData(customer, false);
			}
		}
		private void FillDetails(int orderID)
		{

			NorthwindDataTableAdapters.Order_DetailsTableAdapter detailsCommand = new NorthwindDataTableAdapters.Order_DetailsTableAdapter();
			detailsCommand.Fill(this.DataSet.Order_Details, orderID);
		}
		private NorthwindData.CustomersRow GetCustomerRow(string customerID)
		{
			NorthwindDataTableAdapters.CustomersTableAdapter custAdapter = new NorthwindDataTableAdapters.CustomersTableAdapter();
			NorthwindData.CustomersDataTable table = null;
			table = custAdapter.GetData(customerID);
			if (table.Rows.Count > 0)
			{
				return (NorthwindData.CustomersRow)table.Rows[0];
			}
			else
			{
				return null;
			}
		}


		private void SetBindings()
		{

			this.jsmcEmployeeID.SetDataBinding(NorthwindApp.NorthwindApplication.GetEmployeeList(), "");
			this.jsgxDetails.DropDowns["Products"].SetDataBinding(NorthwindApp.NorthwindApplication.GetProductList(), "");
			this.jsudShipVia.ValueList.PopulateValueList((System.Collections.IEnumerable)NorthwindApp.NorthwindApplication.GetShippersList(), "ShipperID", "CompanyName", "SmallIcon", Color.Magenta, new Size(16, 16));

			this.txtCustomerID.DataBindings.Add("Text", this.DataSet, "Orders.CustomerID");
			this.txtShipName.DataBindings.Add("Text", this.DataSet, "Orders.ShipName");
			this.txtShipAddress.DataBindings.Add("Text", this.DataSet, "Orders.ShipAddress");
			this.txtShipCity.DataBindings.Add("Text", this.DataSet, "Orders.ShipCity");
			this.txtShipRegion.DataBindings.Add("Text", this.DataSet, "Orders.ShipRegion");
			this.txtShipPostalCode.DataBindings.Add("Text", this.DataSet, "Orders.ShipPostalCode");
			this.txtShipCountry.DataBindings.Add("Text", this.DataSet, "Orders.ShipCountry");
			this.jsmcEmployeeID.DataBindings.Add("Value", this.DataSet, "Orders.EmployeeID");
			this.jsudShipVia.DataBindings.Add("Value", this.DataSet, "Orders.ShipVia");
			this.jsdtOrderDate.DataBindings.Add("BindableValue", this.DataSet, "Orders.OrderDate");
			this.jsdtRequiredDate.DataBindings.Add("BindableValue", this.DataSet, "Orders.RequiredDate");
			this.jsdtShippedDate.DataBindings.Add("BindableValue", this.DataSet, "Orders.ShippedDate");
			this.nedtFreight.DataBindings.Add("Value", this.DataSet, "Orders.Freight");
			this.jsgxDetails.SetDataBinding(this.DataSet, "Orders.Orders_OrderDetails");
			this.CalculateTotals();

		}

		private void CalculateTotals()
		{
			decimal subTotal = 0M;
			subTotal = Convert.ToDecimal(this.jsgxDetails.GetTotal(this.jsgxDetails.RootTable.Columns["DetailTotal"], AggregateFunction.Sum));
			this.txtSubTotal.Text = subTotal.ToString("c");
			if (! System.Convert.IsDBNull(DataRowView["Freight"]))
			{
				subTotal += System.Convert.ToDecimal(DataRowView["Freight"]);
			}
			this.txtTotal.Text = subTotal.ToString("c");


		}


		private void jsgxDetails_LoadingRow(object sender, Janus.Windows.GridEX.RowLoadEventArgs e)
		{
			if (e.Row.RowType == RowType.Record)
			{
				e.Row.Cells["DetailTotal"].Value = System.Convert.ToDecimal(System.Convert.ToDecimal(e.Row.Cells["Quantity"].Value) * (decimal)e.Row.Cells["UnitPrice"].Value * (decimal)(1f - (float)e.Row.Cells["Discount"].Value));
			}
		}

		private void jsgxDetails_RecordUpdated(object sender, System.EventArgs e)
		{
			this.CalculateTotals();
		}

		private void jsgxDetails_RecordAdded(object sender, System.EventArgs e)
		{
			this.CalculateTotals();
		}

		private void jsgxDetails_RecordsDeleted(object sender, System.EventArgs e)
		{
			this.CalculateTotals();
		}


		private void FillCustomerData(NorthwindData.CustomersRow customer, bool fillShipInfo)
		{
			if (customer != null)
			{
				if (! customer.IsAddressNull())
				{
					this.txtCustAddress.Text = customer.Address;
				}
				else
				{
					this.txtCustAddress.Text = "";
				}
				if (! customer.IsCityNull())
				{
					this.txtCustCity.Text = customer.City;
				}
				else
				{
					this.txtCustCity.Text = "";
				}
				if (! customer.IsCompanyNameNull())
				{
					this.txtCustCompanyName.Text = customer.CompanyName;
				}
				else
				{
					this.txtCustCompanyName.Text = "";
				}
				if (! customer.IsCountryNull())
				{
					this.txtCustCountry.Text = customer.Country;
				}
				else
				{
					this.txtCustCountry.Text = "";
				}
				if (! customer.IsPostalCodeNull())
				{
					this.txtCustPostalCode.Text = customer.PostalCode;
				}
				else
				{
					this.txtCustPostalCode.Text = "";
				}
				if (! customer.Is_RegionNull())
				{
					this.txtCustRegion.Text = customer._Region;
				}
				else
				{
					this.txtCustRegion.Text = "";
				}
				if (fillShipInfo)
				{
					NorthwindData.OrdersRow order = null;
					order = (NorthwindData.OrdersRow)DataRowView.Row;
					this.CurrencyManager.SuspendBinding();

					order["CustomerID"] = customer["CustomerID"];
					order["ShipAddress"] = customer["Address"];
					order["ShipCity"] = customer["City"];
					order["ShipCountry"] = customer["Country"];
					order["ShipName"] = customer["CompanyName"];
					order["ShipRegion"] = customer["Region"];
					order["ShipPostalCode"] = customer["PostalCode"];
					this.CurrencyManager.ResumeBinding();
				}

			}
		}

		private void txtCustomerID_Validating(object sender, System.ComponentModel.CancelEventArgs e)
		{
			NorthwindData.CustomersRow customer = null;
			if (this.txtCustomerID.Text.Length > 0)
			{
				if (txtCustomerID.Text != txtCustomerID.Tag)
				{
					customer = this.GetCustomerRow(this.txtCustomerID.Text);
					if (customer == null)
					{
						MessageBox.Show("Customer with ID = '" + txtCustomerID.Text + "' does not exist.", NorthwindApp.MessageCaption);
						e.Cancel = true;
					}
					else
					{
						this.FillCustomerData(customer, true);
					}
				}
			}
		}

		private void txtCustomerID_Enter(object sender, System.EventArgs e)
		{
			txtCustomerID.Tag = txtCustomerID.Text;
		}

		private void jsgxDetails_CellUpdated(object sender, Janus.Windows.GridEX.ColumnActionEventArgs e)
		{
			switch (e.Column.Key)
			{
				case "ProductID":
					this.jsgxDetails.SetValue("ProductName", this.jsgxDetails.GetValue("ProductID"));
					break;
				case "ProductName":
					this.jsgxDetails.SetValue("ProductID", this.jsgxDetails.GetValue("ProductName"));
					break;
				case "Quantity":
				case "UnitPrice":
				case "Discount":
					CalculateDetailTotal();
					break;
			}


		}
		private void CalculateDetailTotal()
		{
			GridEXRow row = null;
			row = this.jsgxDetails.GetRow();
			try
			{
				decimal total = 0M;
                total = System.Convert.ToDecimal(System.Convert.ToDecimal(row.Cells["Quantity"].Value) * (decimal)row.Cells["UnitPrice"].Value * (decimal)(1 - (float)row.Cells["Discount"].Value));
				this.jsgxDetails.SetValue("DetailTotal", total);
			}
			catch
			{
				this.jsgxDetails.SetValue("DetailTotal", 0);
			}
		}
		private void jsgxDetails_DropDownHide(object sender, Janus.Windows.GridEX.DropDownHideEventArgs e)
		{
			//If e.ValueSelected Then
			//    'get the Id
			//    Dim id As Integer = CInt(Me.jsgxDetails.GetValue(e.Column))
			//    'use this id to locate the DataRow in the Products table if Products
			//    'table is the datasource of the dropdown
			//    Dim product As NorthwindDataSet.ProductsRow = Me.dsNorthWind.Products.Rows.Find(id)
			//    If Not product Is Nothing Then
			//        Me.jsgxDetails.SetValue("UnitPrice", product.UnitPrice)
			//        'Set other column values here
			//        Me.jsgxDetails.SetValue("ProductID", Me.jsgxDetails.GetValue("ProductName"))
			//    End If
			//End If
		}

		private void btnShipppers_Click(object sender, System.EventArgs e)
		{
			frmShippers frm = null;
			frm = new frmShippers();
			NorthwindDataTableAdapters.ShippersTableAdapter shippersAdapter = new NorthwindDataTableAdapters.ShippersTableAdapter();
			shippersAdapter.ClearBeforeFill = true;
			shippersAdapter.Fill(this.dsNorthwind.Shippers);
			frm.Data = new DataView(this.dsNorthwind.Shippers);
			if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				this.jsudShipVia.ValueList.Clear();
				this.jsudShipVia.ValueList.PopulateValueList(this.dsNorthwind.Shippers.DefaultView, "ShipperID", "CompanyName", "SmallIcon", Color.Magenta, new Size(16, 16));
			}
			frm.Dispose();

		}
		private bool ValidateDetailRow()
		{
			GridEXRow currentRow = jsgxDetails.GetRow();
			if (System.Convert.IsDBNull(currentRow.Cells["ProductID"].Value))
			{
				MessageBox.Show("Product can not be empty.");
				this.jsgxDetails.CurrentColumn = this.jsgxDetails.RootTable.Columns["ProductID"];
				this.jsgxDetails.Focus();
				return false;
			}
			if (System.Convert.IsDBNull(currentRow.Cells["Quantity"].Value))
			{
				MessageBox.Show("Enter the quantity.");
				this.jsgxDetails.CurrentColumn = this.jsgxDetails.RootTable.Columns["Quantity"];
				this.jsgxDetails.Focus();
				return false;
			}
			if (System.Convert.IsDBNull(currentRow.Cells["UnitPrice"].Value))
			{
				MessageBox.Show("Enter the Unit Price.");
				this.jsgxDetails.CurrentColumn = this.jsgxDetails.RootTable.Columns["UnitPrice"];
				this.jsgxDetails.Focus();
				return false;
			}
			if (System.Convert.IsDBNull(currentRow.Cells["Discount"].Value))
			{
				this.jsgxDetails.SetValue("Discount", 0);
				return false;
			}
			return true;
		}

		private void jsgxDetails_AddingRecord(object sender, System.ComponentModel.CancelEventArgs e)
		{
			e.Cancel = ! ValidateDetailRow();
		}

		private void jsgxDetails_UpdatingRecord(object sender, System.ComponentModel.CancelEventArgs e)
		{
			e.Cancel = ! ValidateDetailRow();
		}

		private void nedtFreight_Validated(object sender, System.EventArgs e)
		{
			this.CalculateTotals();
		}




		private void txtCustomerID_ButtonClick(object sender, System.EventArgs e)
		{
			frmSelectCustomer customerDialog = new frmSelectCustomer();
			NorthwindData.CustomersRow customer = null;
			string prevValue = this.txtCustomerID.Text;
			bool fillShipInfo = false;
			string customerID = "";
            if (!System.Convert.IsDBNull(DataRowView["CustomerID"]))
            {
                customerID = (string)DataRowView["CustomerID"];
            }

            customer = customerDialog.SelectCustomer(prevValue);

			if (customer != null)
			{
				if (customer.CustomerID != prevValue)
				{
					fillShipInfo = true;
				}
			}
			FillCustomerData(customer, fillShipInfo);
		}
	}

} //end of root namespace